﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using RuleCode.Table;

namespace map.PayEase
{
    public partial class ImmediateResult : System.Web.UI.Page
    {
        public string[] allParmaKeys = new string[] { "v_oid", "v_pmode", "v_pstatus", "v_pstring",
                        "v_md5info", "v_moneytype", "v_amount", "v_md5money","v_sign" };

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string errorMsg = InitPayEase();
                if (errorMsg != string.Empty)
                {                    
                    Response.Write("error");
                    errorMsgSpan.InnerHtml = errorMsg;
                }
                else
                {
                    Response.Write("sent");
                }
                GoodResultDiv.Style["display"] = (errorMsg == string.Empty) ? "block" : "none";
                BadResultDiv.Style["display"] = (errorMsg == string.Empty) ? "none" : "block";
            }
        }

        #region 辅助方法
        /// <summary>
        /// 获取变量值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="allQueryText"></param>
        /// <returns></returns>
        private string getQueryString(string key, string allQueryText)
        {
            string result = string.Empty;
            int start = allQueryText.IndexOf(key + "=");
            if (start >= 0)
            {
                int end = allQueryText.IndexOf("&", start);
                if (end > (start + key.Length + 1))
                {
                    result = allQueryText.Substring(start + key.Length + 1, end - start - key.Length - 1);
                }
                else
                {
                    if (end == -1)
                    {
                        result = allQueryText.Substring(start + key.Length + 1, allQueryText.Length - start - key.Length - 1);
                    }
                }
            }
            return result;
        }


        private string  InitPayEase()
        {
            string errorMsg = string.Empty;

            string queryStr = HttpUtility.UrlDecode(Request.ServerVariables["QUERY_STRING"], Encoding.GetEncoding("Gb2312"));
                        
            string v_oid = getQueryString("v_oid", queryStr);
            string v_pmode = getQueryString("v_pmode", queryStr);
            string v_pstatus = getQueryString("v_pstatus", queryStr);
            string v_pstring = getQueryString("v_pstring", queryStr);
            string v_md5info = getQueryString("v_md5info", queryStr);
            string v_moneytype = getQueryString("v_moneytype", queryStr);
            string v_amount = getQueryString("v_amount", queryStr);
            string v_md5money = getQueryString("v_md5money", queryStr);
            string v_sign = getQueryString("v_sign", queryStr);

            v_oidSpan.InnerHtml = v_oid;
            v_pmodeSpan.InnerHtml = v_pmode;
            v_pstringSpan.InnerHtml = v_pstring;
            v_amountSpan.InnerHtml = v_amount;
            v_moneytypeSpan.InnerText = (v_moneytype =="0")?"人民币":((v_moneytype =="1")?"美元":"未知错误"); 

            foreach (string key in allParmaKeys)
            {
                if (getQueryString(key, queryStr) == string.Empty)
                {
                    errorMsg = "充值失败;";
                }
            }

            ClassHmac2003.ClassHmac cc = new ClassHmac2003.ClassHmac();
            string md5infoText = v_oid + v_pstatus + v_pstring + v_pmode;
            string md5info = cc.hex_hmac_md5(md5infoText, PayEaseUtil.md5_key);

            string md5moneyText = v_amount + v_moneytype;
            string md5money = cc.hex_hmac_md5(md5moneyText, PayEaseUtil.md5_key);

            if (md5info != v_md5info || md5money != v_md5money)
            {
                errorMsg += "指纹验证失败;";
            }

            //RSA验证
            string strSource = v_oid + v_pstatus + v_amount + v_moneytype;

            RSA_MD5 rsa = new RSA_MD5();
            int d = rsa.PublicVerifyMD5(Server.MapPath("Public1024.key"), v_sign, strSource);

            if (d != 0)
            {
                errorMsg += "RSA验证失败;";
            }


            cbPayEaseReturnTrans returnTrans = cbPayEaseReturnTrans.Find("v_oid like '%"+v_oid +"%'");
            if (returnTrans.Count <= 0)
            {
                try
                {
                    returnTrans.New();
                    returnTrans.v_count.Value = 1;
                    returnTrans.v_oid.Value = v_oid;
                    returnTrans.v_pmode.Value = v_pmode;
                    returnTrans.v_pstatus.Value = v_pstatus;
                    returnTrans.v_pstring.Value = v_pstring;
                    returnTrans.v_md5info.Value = v_md5info;
                    returnTrans.v_moneytype.Value = v_moneytype;
                    returnTrans.v_amount.Value = v_amount;
                    returnTrans.v_md5money.Value = v_md5money;
                    returnTrans.v_sign.Value = v_sign;
                    returnTrans.ReturnType.Value = RuleCode.Enum.PayEaseTranType.ImmiReturn;
                    returnTrans.FinalResult.Value = errorMsg;
                    returnTrans.OriginResult.Value = queryStr;
                    returnTrans.Insert();

                    returnTrans.CurrentIndex = 0;
                }
                catch (Exception e)
                {
                    errorMsg += e.Message + ";";
                }
            }
            else
            {
                errorMsg += "该订单日志已经记录过;";
            }

            double amount = 0.0;
            try
            {
                amount = Convert.ToDouble (v_amount );
            }
            catch { }


            if (errorMsg == string.Empty )
            {
                cbuser user = cbuser.Find("recid in (select v_ordername as recid from dbo.cbPayEaseOrderTrans where v_oid='"+v_oid +"')");
                if (user.Count > 0 && user.cbuserid.Value == AliApi.appUserId)
                {

                    DateTime curDate = DateTime.Now;
                    cbmoneytrans moneytran = cbmoneytrans.Find("RefRecID='" + v_oid + "'");
                    if (moneytran.Count > 0)
                    {
                        errorMsg += "该订单已经充值成功,不能继续使用;";
                    }
                    else
                    {
                        try
                        {


                            //moneytran.New();
                            //moneytran.cbmoney.Value = -amount;
                            //moneytran.cbmoneytrantype.Value = MONEY_TransType.BankOut ;
                            //moneytran.cbuserid.Value = user.cbuserid.Value;
                            //moneytran.jccreatedate.Value = curDate;
                            //moneytran.jccreatetime.Value = (int)(curDate.TimeOfDay.TotalSeconds);
                            //moneytran.jcdesc.Value = queryStr;
                            //moneytran.NoYes_dongjie.Value = RuleCode.Enum.NoYes.No;
                            //moneytran.RefRecID.Value = v_oid  ;
                            //moneytran.RefTable.Value = "cbPayEaseReturnTrans";
                            //moneytran.Insert();

                            moneytran.New();
                            moneytran.cbmoney.Value = amount;
                            moneytran.cbmoneytrantype.Value = MONEY_TransType.ChargeIn;
                            moneytran.cbuserid.Value = user.cbuserid.Value;
                            moneytran.jccreatedate.Value = curDate;
                            moneytran.jccreatetime.StringValue = curDate.ToLongTimeString();
                            moneytran.jcdesc.Value = queryStr;
                            moneytran.NoYes_dongjie.Value = RuleCode.Enum.NoYes.No;
                            moneytran.RefRecID.Value = v_oid;
                            moneytran.RefTable.Value = "cbPayEaseReturnTrans";
                            moneytran.Insert();

                            user.cbmoney.Value += amount;
                            user.cbmoneyZ.Value += amount;
                            user.Modify();
                        }
                        catch (Exception me)
                        {
                            errorMsg += me.Message;
                        }
                    }
                }
                else
                {
                    errorMsg = "对不起，该用户不存在";
                }
            }

            return errorMsg;
        }

        private string GetPStatusInfo(string pstatus)
        {
            switch (pstatus)
            {
                case "1":
                    {
                        return "已提交，使用的是非实时银行卡进行扣款";
                    }
                case "20":
                    {
                        return "支付成功，使用的是实时银行卡进行扣款";
                    }
                case "30":
                    {
                        return "支付失败，使用的是实时银行卡进行扣款";
                    }
                default:
                    {
                        return "未知错误";
                    }
            }
        }
        #endregion
    }
}
